package com.woyao;

import android.Manifest;
import android.app.Activity;
import android.app.Application;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.NotificationCompat;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.Chance;
import com.woyao.core.model.GetNextChanceResponse;
import com.woyao.core.model.ItemSummary;
import com.woyao.core.model.Partner;
import com.woyao.core.model.ProfileResponse;
import com.woyao.core.model.User;
import com.woyao.core.service.AccountService;
import com.woyao.core.service.ChanceService;
import com.woyao.core.util.CollectionUtil;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;
import com.woyao.core.util.StringUtil;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;

import static com.woyao.R.id.avatar;
import static com.woyao.WoyaoooApplication.context;
import static com.woyao.WoyaoooApplication.userId;

public class ChanceActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {


    Integer lastBid = 0;
    private Chance chance = new Chance();

    private TextView creatorName;
    private CircleImageView creatorAvatar;


    private TextView fulltitle;
    private LinearLayout demandPic;
    private LinearLayout demandInfo;
    private  LinearLayout pics;
    private LinearLayout orgInfo;
    private LinearLayout managerInfo;
    private LinearLayout partnerInfo;
    private LinearLayout matchExplan;

    Button connectBtn;
    Button ignoreBtn;

    Button referOtherBtn;


    ProgressDialog progressDialog;

    private float mPosX;
    private float mPosY;
    private float mCurrentPosX;
    private float mCurrentPosY;

    private boolean loading = false;

    private NotificationManager nm;
    private Notification n;

    public static final int NOTIFY_ID = 1;



    private ClipboardManager myClipboard;
    private ClipData myClip;

    private ScrollView mainScrollView;

    String longitude = "0.0";
    String latitude = "0.0";

    TextView username ;   //  current user name
    private CircleImageView user_avatar;

    Integer REFER_CODE =  917;
    Integer APPLY_CODE =  111;
    Integer DEMAND_CODE =  234;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chance);


        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close){

            @Override
            public void onDrawerOpened(View drawerView) {

                SharedPreferences shared = getSharedPreferences("login", MODE_PRIVATE);
                Boolean hasLogin = shared.getBoolean("logged", false);

                if (hasLogin ) {

                    user_avatar = (CircleImageView) findViewById(avatar);
                    username = (TextView) findViewById(R.id.usernameText);

                    username.setText(WoyaoooApplication.displayname);

                    Picasso.with(ChanceActivity.this)
                            .load(WoyaoooApplication.snailview)
                            .into(user_avatar);

                } else{
                    Intent intent = new Intent(ChanceActivity.this, RegisterActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                }
            }
        };


        drawer.addDrawerListener(toggle);
        toggle.syncState();

        user_avatar = (CircleImageView) findViewById(avatar);
        username = (TextView) findViewById(R.id.usernameText);

        loadProfile();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);


        fulltitle = (TextView) findViewById(R.id.id_fulltitle);

        creatorName = (TextView) findViewById(R.id.id_displayname);

        matchExplan  = (LinearLayout)  findViewById(R.id.match_explan);


        creatorAvatar = (CircleImageView) findViewById(R.id.creator_avatar);
        demandPic = (LinearLayout) findViewById(R.id.demand_pic);
        demandInfo = (LinearLayout) findViewById(R.id.demand_info);
        pics = (LinearLayout) findViewById(R.id.pics);


        orgInfo = (LinearLayout)  findViewById(R.id.org_info);
        partnerInfo = (LinearLayout)  findViewById(R.id.partner_info);
        managerInfo = (LinearLayout)  findViewById(R.id.manager_info);

        referOtherBtn = (Button) findViewById(R.id.demand_referothers);

        referOtherBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences shared = getSharedPreferences("login", MODE_PRIVATE);
                Boolean hasLogin = shared.getBoolean("logged", false);

                if (hasLogin ) {
                    Intent intent = new Intent();
                    intent.setClass(ChanceActivity.this, ReferActivity.class);
                    intent.putExtra( "title", chance.getTitle());
                    intent.putExtra( "id", chance.getId());
                    startActivityForResult( intent,REFER_CODE );
                } else{
                    Intent intent = new Intent(ChanceActivity.this, RegisterActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                }
            }
        });



        connectBtn = (Button) findViewById(R.id.tryConnect);

        connectBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SharedPreferences shared = getSharedPreferences("login", MODE_PRIVATE);
                Boolean hasLogin = shared.getBoolean("logged", false);

                if (hasLogin ) {
                    applyIt();
                } else{
                    Intent intent = new Intent(ChanceActivity.this, RegisterActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                }

            }
        });

        ignoreBtn = (Button) findViewById(R.id.tryIgnore);

        ignoreBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if  (!chance.getStatus().equals("apply")) {
                    getNext("next", "ignore");
                }
            }
        });



        mainScrollView = (ScrollView) findViewById(R.id.mainScollView);
        mainScrollView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    // 按下
                    case MotionEvent.ACTION_DOWN:
                        mPosX = event.getX();
                        mPosY = event.getY();
//                        Log.e("woyaooo", "ACTION_DOWN");

                        break;
                    // 移动
                    case MotionEvent.ACTION_MOVE:
                        mCurrentPosX = event.getX();
                        mCurrentPosY = event.getY();

                        if (mCurrentPosX - mPosX > 60 && Math.abs(mCurrentPosY - mPosY) < 15) {
                            Log.e("woyaooo", "向右");
                            getNext("next","");
                            return true;
                        } else if (mCurrentPosX - mPosX < -60 && Math.abs(mCurrentPosY - mPosY) < 15) {
                            Log.e("woyaooo", "向左");
                            getNext("previous","");
                            return true;

                        }
//                        else if (mCurrentPosY - mPosY > 35 && Math.abs(mCurrentPosX - mPosX) < 10) {
//                            Log.e("woyaooo", "向下");
//                            getNext();
//                        } else if (mCurrentPosY - mPosY < -35 && Math.abs(mCurrentPosX - mPosX) < 10) {
//                            Log.e("woyaooo", "向上");
//                            getNext();
//                        } else {
////                            Intent intent = new Intent();
////                            intent.setClass(ChanceActivity.this, DetailsActivity.class);
////                            intent.putExtra("fromChance", chance);
////                            startActivity(intent);
//                        }

                        Log.e("woyaooo", "ACTION_MOVE X" + (mCurrentPosX - mPosX) + " Y:" + (mCurrentPosY - mPosY));
                        break;
                    // 拿起
                    case MotionEvent.ACTION_UP:
//                        if (Math.abs(mCurrentPosY - mPosY) < 20 && Math.abs(mCurrentPosX - mPosX) < 20)

                        break;
                    default:
                        break;
                }
                return false;
            }
        });

//        main.setVisibility(View.GONE);


        Uri uri = getIntent().getData();
        if (uri != null ) {
            try {
                StringBuilder sb = new StringBuilder();
                // 唤起链接
                sb.append("string : ").append(getIntent().getDataString()).append("\n");
                sb.append("scheme : ").append(uri.getScheme()).append("\n");
                sb.append("host : ").append(uri.getHost()).append("\n");
                sb.append("port : ").append(uri.getPort()).append("\n");
                sb.append("path : ").append(uri.getPath()).append("\n");
                // 接收唤起的参数
                sb.append("bid : ").append(uri.getQueryParameter("bid")).append("\n");

//                Common.alert(this, sb.toString());

                String bid = uri.getQueryParameter("bid");

                if (bid != null) {
                    getChance(Integer.parseInt(bid));

                } else {
                    getNext("next", "");
                }
            } catch (Exception e) {
                e.printStackTrace();
                getNext("next", "");
            }
        }else{
            getNext("next", "");
        }

    }



    private void complain(  ){
        Intent intent = new Intent();
        intent.putExtra("mid", 0 );
        intent.putExtra("title", "吐槽");
        intent.setClass(ChanceActivity.this, TalkActivity.class);
        startActivity(intent);

    }


    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.chance, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();



        if (id == R.id.nav_history ) {

            SharedPreferences shared = getSharedPreferences("login", MODE_PRIVATE);
            Boolean hasLogin = shared.getBoolean("logged", false);

            if (hasLogin ) {
                Intent intent = new Intent();
                intent.setClass(ChanceActivity.this, MyRelationActivity.class);
                startActivity(intent);
            } else{
                Intent intent = new Intent(ChanceActivity.this, RegisterActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
//            displayReferContent();

        }


        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_help) {
            Intent intent = new Intent();
            intent.setClass(ChanceActivity.this, WebviewActivity.class);
            intent.putExtra("link", "http://www.woyaooo.com/charge.html");
            startActivity(intent);
        } else if (id == R.id.nav_my_money) {
            Intent intent = new Intent();
            intent.putExtra("money", 100.0);
            intent.setClass(ChanceActivity.this, MoneyActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_my_demand) {
            Intent intent = new Intent();
            intent.setClass(ChanceActivity.this, MyDemandActivity.class);
            intent.putExtra("from", "main");
            startActivityForResult(intent,400);
        }  else if (id == R.id.nav_comment) {
            complain();
        } else if (id == R.id.nav_logout) {
            userId = null;
            WoyaoooApplication.username = null;
            SharedPreferences preferences = getSharedPreferences("login", 0);
            SharedPreferences.Editor editor = preferences.edit();
            editor.clear();
            editor.commit();
            finish();
            Intent intent = new Intent(ChanceActivity.this, Welcome2Activity.class);
            startActivity(intent);
        } else if (id == R.id.nav_my_account) {
            Intent intent = new Intent();
            intent.setClass(ChanceActivity.this, AccountActivity.class);
            intent.putExtra("from", "main");
            startActivity(intent);
        }
        else if (id == R.id.nav_my_member) {
            Intent intent = new Intent();
            intent.setClass(ChanceActivity.this, MyMemberActivity.class);
            intent.putExtra("from", "main");
            startActivity(intent);
        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);

        return true;
    }

    private void getNext( final String direction, final String ignore) {
        if (!chance.getStatus().equals("apply") && chance.getObject_status().equals("apply")){

            Dialog alertDialog = new AlertDialog.Builder(ChanceActivity.this).
                    setTitle("信息").
                    setMessage("对方希望与您沟通合作，你忽略吗？").
                    setIcon(R.drawable.ic_launcher).
                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            getNextChance( direction, ignore);
                        }
                    }).
                    setNegativeButton("取消", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    }).
                    create();
            alertDialog.show();
        } else {
            getNextChance( direction, ignore);
        }

    }
    private void getNextChance(final String direction, final String ignore){


        ConnectivityManager connMgr = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo == null || !networkInfo.isConnected()) {
            Dialog alertDialog = new AlertDialog.Builder(this).
                    setTitle("错误").
                    setMessage("没有网络，请检查您的设置！").
                    setIcon(R.drawable.ic_launcher).
                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            getNext(direction,ignore) ;
                        }
                    }).
                    create();
            alertDialog.show();

            Common.showSnack(ChanceActivity.this,creatorName,"没有网络，请检查您的设置！");
            return;
        }

        if (loading){
            Toast.makeText(this,"正在加载...",Toast.LENGTH_SHORT).show();
            return;
        }
        progressDialog = new ProgressDialog(ChanceActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("加载下一个机会···");
        progressDialog.show();
        loading = true;

        getCurrentLocation( ChanceActivity.this);

        AsyncTask<Void, Void, GetNextChanceResponse> task = new AsyncTask<Void, Void, GetNextChanceResponse>() {
            @Override
            protected GetNextChanceResponse doInBackground(Void... params) {
                ChanceService svc = ServiceFactory.get(ChanceService.class);
                Call<GetNextChanceResponse> responseCall = svc.next(userId,lastBid,longitude,latitude ,direction, ignore  );
                GetNextChanceResponse ret = null ;
                try {
                    ret = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = null;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final GetNextChanceResponse resp) {
                if (resp != null ) {
                    if (resp.isSuccess()) {
                        Chance chance = resp.getContent();

                        if (chance != null) {
                            renderChance(chance);
                            progressDialog.dismiss();
                            loading = false;
                            return;
                        }else {
                            Common.showSnack(ChanceActivity.this, creatorName, "没有成功获取新机会！");
                        }
                    }else{
                        modifyDemand( );
                    }
                }else {
                    Common.showSnack(ChanceActivity.this, creatorName, "请检查网络后重试！");
                }
                ChanceActivity.this.setTitle("合作机会");
                lastBid = 0;
                progressDialog.dismiss();
                loading = false;

            }

            @Override
            protected void onCancelled() {

                progressDialog.dismiss();
                loading = false;
                Common.showSnack(ChanceActivity.this, creatorName, "没有成功获取新机会！");

            }
        };
        task.execute((Void) null);

    }

    private void getChance( final Integer bid ){


        progressDialog = new ProgressDialog(ChanceActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("加载下一个机会···");
        progressDialog.show();

        AsyncTask<Void, Void, GetNextChanceResponse> task = new AsyncTask<Void, Void, GetNextChanceResponse>() {
            @Override
            protected GetNextChanceResponse doInBackground(Void... params) {
                ChanceService svc = ServiceFactory.get(ChanceService.class);
                Call<GetNextChanceResponse> responseCall = svc.getChance(userId,bid );
                GetNextChanceResponse ret = null ;
                try {
                    ret = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = null;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final GetNextChanceResponse resp) {
                if (resp != null ) {
                    if (resp.isSuccess()) {
                        Chance chance = resp.getContent();

                        if (chance != null) {
                            renderChance(chance);
                            progressDialog.dismiss();
                            return;
                        }else {
                            Common.showSnack(ChanceActivity.this, creatorName, "没有成功获取新机会！");
                        }
                    }else{
                        Common.showSnack(ChanceActivity.this, creatorName,resp.getCondition());
                    }
                }else {
                    Common.showSnack(ChanceActivity.this, creatorName, "请检查网络后重试！");
                }

                lastBid = 0;
                progressDialog.dismiss();


                chance = null;

            }

            @Override
            protected void onCancelled() {

                progressDialog.dismiss();
                Common.showSnack(ChanceActivity.this, creatorName, "没有成功获取新机会！");

            }
        };
        task.execute((Void) null);

    }

    private  void modifyDemand( ){
//    Toast.makeText(ChanceActivity.this,"没有合适的机会了，请修改您的合作需求",Toast.LENGTH_SHORT) ;

    Dialog alertDialog = new AlertDialog.Builder(this).
            setTitle("信息").
            setMessage("没有合适的机会了，请修改您的合作需求").
            setIcon(R.drawable.ic_launcher).
            setPositiveButton("确定", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent();
                    intent.setClass(ChanceActivity.this, DemandActivity.class);
                    intent.putExtra("from", "chance"  );
                    intent.putExtra("id", context );
                    startActivityForResult(intent,DEMAND_CODE);
                }
            }).
            create();
    alertDialog.show();


}

    private void renderChance(final Chance chance) {
        // 不同状态的机会控制背景色？
        mainScrollView.setBackgroundColor(ContextCompat.getColor(this,R.color.colorWhite));
        mainScrollView.fullScroll(ScrollView.FOCUS_UP);

        this.chance = chance;
        if (chance == null) {
            return;
        }
//        notification( chance.getOrg());

        lastBid = chance.getId();

        if (chance.getOrder() > 0 ) {
            this.setTitle("合作机会（"  + Integer.toString( chance.getOrder())  + "/" +  Integer.toString( chance.getTotal()) +"）"  );
        }else{
            this.setTitle("合作机会");
        }



        connectBtn.setText(chance.getStatus_text());

        fulltitle.setText(chance.getTitle());

        creatorAvatar.setImageResource(R.drawable.no_avartar);

        Picasso.with(this)
                .load(chance.getManager().get("snailview"))
                .into(creatorAvatar );



        creatorName.setText( chance.getManager().get("displayname")  );

        displayDemand();

        displayOrg();

        displayManager();

        displayPartners();

        displayExplanation();


    }



    private void displayDemand() {

        demandPic.removeAllViews();

        Common.showMedia( this,chance.getImage(),demandPic);

        demandInfo.removeAllViews();

        List<Map<String, String>> businessInfos = new ArrayList<>();
        if (chance.getDescription() != null && !chance.getDescription().trim().equals("")) {
            businessInfos.add(new HashMap<String, String>() {{
                put("name", "需求描述");
                put("info", chance.getDescription().trim());
            }});
        }

        if (chance.getHow() != null && !chance.getHow().equals("")) {
            businessInfos.add(new HashMap<String, String>() {{
                put("name", "合作方式");
                put("info", chance.getHow());
            }});
        }


        if (chance.getRelation() != null  && !chance.getRelation().equals("") ) {
            businessInfos.add(new HashMap<String, String>() {{
                put("name", "合作行业");
                put("info", chance.getRelation());
            }});
        }

        if (chance.getInclude() != null  && !chance.getInclude().equals("") ) {
            businessInfos.add(new HashMap<String, String>() {{
                put("name", "合作区域");
                put("info", chance.getInclude());
            }});
        }

        if ( chance.getBudget() > 0) {
            businessInfos.add(new HashMap<String, String>() {{
                put("name", "预算");
                put("info", chance.getBudget() + "元");
            }});
        }

        if ( chance.getCharge() > 0) {
            businessInfos.add(new HashMap<String, String>() {{
                put("name", "费用");
                put("info", chance.getCharge() + "元");
            }});
        }

        if ( chance.getBidding() > 0) {
            businessInfos.add(new HashMap<String, String>() {{
                put("name", "悬赏介绍");
                put("info", chance.getBidding() + "元");
            }});
        }


        businessInfos.add(new HashMap<String, String>() {{
            put("name", "发布时间");
            put("info",   new SimpleDateFormat("yyyy年MM月dd日").format( chance.getPublish()) );
        }});

        businessInfos.add(new HashMap<String, String>() {{
            put("name", "需求编号");
            put("info", chance.getId()+"");
        }});

        for(Map<String,String> info : businessInfos){
            if (info.get("info").equals(""))
                continue;
            LinearLayout item = (LinearLayout) LayoutInflater.from(ChanceActivity.this).inflate(R.layout.list_item, null);

            TextView title = (TextView)item.findViewById(R.id.title);
            TextView text = (TextView)item.findViewById(R.id.text);
            title.setText( info.get("name") +":");
            text.setText(info.get("info"));
            demandInfo.addView(item);
        }

        for (Map.Entry<String, String> entry : chance.getResource().entrySet()) {

            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());

            LinearLayout item = (LinearLayout) LayoutInflater.from(ChanceActivity.this).inflate(R.layout.list_item, null);

            TextView title = (TextView)item.findViewById(R.id.title);
            TextView text = (TextView)item.findViewById(R.id.text);
            title.setText( entry.getKey() +":");
            text.setText(entry.getValue());
            demandInfo.addView(item);
        }

        pics.removeAllViews();


        for (String onepic : chance.getPics()){
            Common.showMedia(  this, onepic ,  pics  );
        }
    }

    private  void displayOrg() {

        orgInfo.removeAllViews();


        final Map<String,String> theOrg =  chance.getOrg();

        if ( theOrg.get("id").equals("")){
            orgInfo.setVisibility(View.GONE);
            return;
        }

        LinearLayout item1 = (LinearLayout)LayoutInflater.from(ChanceActivity.this).inflate(R.layout.summary_item, null);
        TextView title1 = (TextView)item1.findViewById(R.id.summary_text);
        title1.setText("企业");
        orgInfo.addView(item1);


        LinearLayout item = (LinearLayout)LayoutInflater.from(ChanceActivity.this).inflate(R.layout.partner_item, null);
        CircleImageView avatar = (CircleImageView)item.findViewById(R.id.partner_avatar);
        LinearLayout content = ( LinearLayout )item.findViewById(R.id.partner_content);
        content.setVisibility(View.INVISIBLE);

        if (StringUtil.notNullOrEmpty(theOrg.get("logo"))) {
            Picasso.with(this)
                    .load(theOrg.get("logo"))
                    .into(avatar );
        } else {
            avatar.setImageResource(R.drawable.no_avartar);
        }

        orgInfo.addView(item);




        List<Map<String, String>> orgList = new ArrayList<>();
        orgList.add(new HashMap<String, String>() {{
            put("name", "组织名称");
            put("info", theOrg.get("title"));
        }});
        orgList.add(new HashMap<String, String>() {{
            put("name", "组织名称");
            put("info", theOrg.get("description"));
        }});
        orgList.add(new HashMap<String, String>() {{
            put("name", "所在行业");
            put("info", theOrg.get("business"));
        }});
        orgList.add(new HashMap<String, String>() {{
            put("name", "认证");
            put("info", theOrg.get("verify"));
        }});
        orgList.add(new HashMap<String, String>() {{
            put("name", "成员数");
            put("info", theOrg.get("member_num"));
        }});
        orgList.add(new HashMap<String, String>() {{
            put("name", "合作伙伴");
            put("info", theOrg.get("partner_num"));
        }});

        for(Map<String,String> info : orgList){
            if (info.get("info").equals(""))
                continue;
            LinearLayout item2 = (LinearLayout) LayoutInflater.from(ChanceActivity.this).inflate(R.layout.list_item, null);
            TextView title = (TextView) item2.findViewById(R.id.title);
            TextView text = (TextView) item2.findViewById(R.id.text);
            title.setText(info.get("name") + "：");
            text.setText(info.get("info"));
            orgInfo.addView(item2);
        }

    }

    private  void displayManager() {
        managerInfo.removeAllViews();
        final Map<String,String> theManager =  chance.getManager();

        LinearLayout item1 = (LinearLayout)LayoutInflater.from(ChanceActivity.this).inflate(R.layout.summary_item, null);
        TextView title1 = (TextView)item1.findViewById(R.id.summary_text);
        title1.setText("负责人");
        managerInfo.addView(item1);

        LinearLayout item = (LinearLayout)LayoutInflater.from(ChanceActivity.this).inflate(R.layout.partner_item, null);
        CircleImageView avatar = (CircleImageView)item.findViewById(R.id.partner_avatar);
        LinearLayout content = ( LinearLayout )item.findViewById(R.id.partner_content);
        content.setVisibility(View.INVISIBLE);

        if (StringUtil.notNullOrEmpty(theManager.get("snailview"))) {
            Picasso.with(this)
                    .load( theManager.get("snailview"))
                    .into(avatar );
        } else {
            avatar.setImageResource(R.drawable.no_avartar);
        }

        managerInfo.addView(item);

        List<Map<String, String>> managersInfolist = new ArrayList<>();


        managersInfolist.add(new HashMap<String, String>() {{
            put("name", "姓名");
            put("info", theManager.get("displayname"));
        }});
        managersInfolist.add(new HashMap<String, String>() {{
            put("name", "地区");
            put("info", theManager.get("location"));
        }});
        managersInfolist.add(new HashMap<String, String>() {{
            put("name", "身份");
            put("info", theManager.get("role"));
        }});
        managersInfolist.add(new HashMap<String, String>() {{
            put("name", "认证");
            put("info", theManager.get("verify"));
        }});



        for(Map<String,String> info : managersInfolist){
            if (info.get("info").equals(""))
                continue;
            LinearLayout item2 = (LinearLayout)LayoutInflater.from(ChanceActivity.this).inflate(R.layout.list_item, null);
            TextView title = (TextView)item2.findViewById(R.id.title);
            TextView text = (TextView)item2.findViewById(R.id.text);
            title.setText(info.get("name") +"：");
            text.setText(info.get("info"));
            managerInfo.addView(item2);
        }
    }

    private  void displayPartners() {


        partnerInfo.removeAllViews();

        if (chance.getPartners().size()  ==0 )
            return;

        LinearLayout item1 = (LinearLayout)LayoutInflater.from(ChanceActivity.this).inflate(R.layout.summary_item, null);
        TextView title1 = (TextView)item1.findViewById(R.id.summary_text);
        title1.setText("达成合作数：" + chance.getPartners().size() + "");
        partnerInfo.addView(item1);


        if(CollectionUtil.notEmpty(chance.getPartners())){
            //合作的人
            for(Partner partner : chance.getPartners()){
                LinearLayout item = (LinearLayout)LayoutInflater.from(ChanceActivity.this).inflate(R.layout.partner_item, null);
                CircleImageView avatar = (CircleImageView)item.findViewById(R.id.partner_avatar);
                TextView title = (TextView)item.findViewById(R.id.partner_title);
                TextView desc = (TextView)item.findViewById(R.id.partner_desc);

                title.setText(partner.getTitle());
                desc.setText(partner.getDescription());

                if (StringUtil.notNullOrEmpty(partner.getImage())) {
                    Picasso.with(this)
                            .load(partner.getImage())
                            .into(avatar );
                } else {
                    avatar.setImageResource(R.drawable.no_avartar);
                }

                partnerInfo.addView(item);
            }
        }
    }

    private  void displayExplanation(){

        matchExplan.removeAllViews();


        LinearLayout item1 = (LinearLayout)LayoutInflater.from(ChanceActivity.this).inflate(R.layout.summary_item, null);
        TextView title1 = (TextView)item1.findViewById(R.id.summary_text);
        title1.setText("机会说明：" );
        matchExplan.addView(item1);

        LinearLayout item = (LinearLayout)LayoutInflater.from(ChanceActivity.this).inflate(R.layout.partner_item, null);
        CircleImageView avatar = (CircleImageView)item.findViewById(R.id.partner_avatar);
        TextView title = (TextView)item.findViewById(R.id.partner_title);
        TextView desc = (TextView)item.findViewById(R.id.partner_desc);

        ItemSummary explan = chance.getExplan();
        title.setText(explan.getTitle());
        desc.setText(explan.getDescription());

        if (StringUtil.notNullOrEmpty(explan.getSnailview())) {
            Picasso.with(this)
                    .load( explan.getSnailview())
                    .into(avatar);
        } else {
            avatar.setImageResource(R.drawable.no_avartar);
        }



        matchExplan.addView(item);

    }






    public  void getCurrentLocation(Activity context) {
        LocationManager locationManager;
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        //获取所有可用的位置提供器
        List<String> providers = locationManager.getProviders(true);
        String locationProvider = null;
        if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            //如果是Network
            locationProvider = LocationManager.NETWORK_PROVIDER;
        } else if (providers.contains(LocationManager.GPS_PROVIDER)) {
            //如果是GPS
            locationProvider = LocationManager.GPS_PROVIDER;
        }  else {
            return ;
        }
        //获取Location
        if ( ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED  && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        }else{
            Location location = locationManager.getLastKnownLocation(locationProvider);
            if (location != null) {
                longitude = location.getLongitude() + "";
                latitude = location.getLatitude() + "";
            }
         }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1: {    // 1 for location
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;
            }
            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

    private void notification( String content){
        try{
            nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

            nm.cancel(ChanceActivity.NOTIFY_ID);

            Bitmap btm = BitmapFactory.decodeResource(getResources(),
                    R.drawable.ic_launcher);

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ChanceActivity.this);
            mBuilder.setSmallIcon(R.drawable.ic_launcher);
            mBuilder.setTicker("新的合作机会-我要合作网");//第一次提示消息的时候显示在通知栏上
            mBuilder.setContentTitle("新的合作机会");
            mBuilder.setContentText(content);

            mBuilder.setNumber(1);
            mBuilder.setLargeIcon(btm);
            mBuilder.setAutoCancel(true);//自己维护通知的消失
            //构建一个Intent
            Intent resultIntent = new Intent(ChanceActivity.this, ChanceActivity.class);
            //封装一个Intent
            PendingIntent resultPendingIntent = PendingIntent.getActivity(ChanceActivity.this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            // 设置通知主题的意图
            mBuilder.setContentIntent(resultPendingIntent);
            mBuilder.setDefaults(NotificationCompat.DEFAULT_ALL);

            nm.notify(NOTIFY_ID, mBuilder.build());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private void loadProfile(){
        if (userId == 0 ){
            return;
        }

        AsyncTask<Void,Void,ProfileResponse> loadTask =
                new AsyncTask<Void, Void, ProfileResponse>() {
                    @Override
                    protected ProfileResponse doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);
                        Call<ProfileResponse> responseCall = svc.getProfile(userId,"android");
                        try {
                            ProfileResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                        e.printStackTrace();
                    }
                        return null;
                    }
                    @Override
                    protected void onPostExecute(final ProfileResponse response) {

                        if(response != null && response.isSuccess()){
                            User usr = response.getContent();
                            String snail = usr.getSnailview();

                            Application application = getApplication();
                            SharedPreferences shared = application.getSharedPreferences("login", MODE_PRIVATE);
                            SharedPreferences.Editor editor = shared.edit();
                            editor.putString("displayname", usr.getDisplayname());
                            WoyaoooApplication.displayname = usr.getDisplayname();
                            editor.putString("snailview", usr.getSnailview());
                            WoyaoooApplication.snailview = usr.getSnailview();
                            editor.commit();
                            context = usr.getDemand_id();

                        }

                    }
                };
        loadTask.execute((Void)null);
    }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == DEMAND_CODE && resultCode == Common.SUCCESS_CODE) {    // apply
            Boolean con = data.getBooleanExtra("changed", true);
            if (con ) {
               getNext("next","");
            }
        }
    }


    private void applyIt( ) {


        AsyncTask<Void, Void, BaseResponse> task =
                new AsyncTask<Void, Void, BaseResponse>() {
                    boolean bizComplete = false;

                    @Override
                    protected BaseResponse doInBackground(Void... params) {
                        ChanceService svc = ServiceFactory.get(ChanceService.class);

                        Call<BaseResponse> responseCall = svc.apply(userId, lastBid,0  ,"" );
                        try {
                            BaseResponse response = responseCall.execute().body();
                            return  response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final BaseResponse response) {
                        progressDialog.dismiss();
                        if ( response != null) {
                            if (response.isSuccess()) {
                                if (chance.getObject_status().equals("apply")){
                                    connectBtn.setText("沟通中");
                                }else {
                                    connectBtn.setText("待对方确认");
                                }
                                chance.setStatus("APPLY");

                                Intent intent = new Intent();
                                intent.putExtra("mid",Integer.parseInt(  response.getMessage()) );
                                intent.putExtra("title", "");
                                intent.setClass(ChanceActivity.this, TalkActivity.class);
                                startActivity(intent);

                            }else{
                                Common.alert(ChanceActivity.this,response.getMessage());
                            }

                        }else{
                            Common.showSnack(ChanceActivity.this, connectBtn,"抱歉,处理失败，请重试。");
                        }
                    }

                    @Override
                    protected void onCancelled() {
                        progressDialog.dismiss();
                        Common.showSnack(ChanceActivity.this, connectBtn,"抱歉,处理失败，请重试。");
                    }
                };
        task.execute((Void) null);

    }



}
